package com.m3839.sdk.common.util;

import android.content.Context;
import android.os.Build;
import android.text.TextUtils;

/**
 * Description:ClipboardUtils
 *
 * @author chenbaoyang
 * @create 2020/8/29 10:27
 */
public class ClipboardUtils {

  /**
   * 复制字符串到剪贴板
   * @param context
   * @param copyStr
   */
  public static void copy(Context context, String copyStr) {
    //兼容性处理3.0以前版本
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
      clipboardManager.setText(copyStr);
    } else {
      android.content.ClipboardManager clipboardManager =
          (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
      clipboardManager.setPrimaryClip(android.content.ClipData.newPlainText(null, copyStr));
    }
  }

  /**
   * 从剪贴板中获得第一个字符串
   * @param activity
   * @return
   */
  public static String paste(Context activity) {
    String pasteStr = "";
    //兼容性处理3.0以前版本
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
      android.text.ClipboardManager clipboardManager = (android.text.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
      if (clipboardManager != null && clipboardManager.hasText()) {
        pasteStr = clipboardManager.getText().toString();
      }
    } else {
      android.content.ClipboardManager clipboardManager = (android.content.ClipboardManager) activity.getSystemService(Context.CLIPBOARD_SERVICE);
      if (clipboardManager != null && clipboardManager.hasPrimaryClip()) {
        CharSequence text = clipboardManager.getPrimaryClip().getItemAt(0).getText();
        pasteStr = TextUtils.isEmpty(text) ? "" : text.toString();
      }
    }
    return pasteStr;
  }
}
